using Microsoft.Extensions.Logging;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using DesktopHelper.Views;

namespace DesktopHelper.Services
{
    public class ScreenshotService
    {
        private readonly ILogger<ScreenshotService> _logger;
        private readonly PinnedImageService _pinnedImageService;

        public ScreenshotService(ILogger<ScreenshotService> logger, PinnedImageService pinnedImageService)
        {
            _logger = logger;
            _pinnedImageService = pinnedImageService;
        }

        /// <summary>
        /// 全屏截图
        /// </summary>
        public Bitmap CaptureFullScreen()
        {
            try
            {
                var bounds = Screen.PrimaryScreen.Bounds;
                var bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
                
                using var graphics = Graphics.FromImage(bitmap);
                graphics.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy);
                
                _logger.LogDebug("全屏截图完成: {Width}x{Height}", bounds.Width, bounds.Height);
                return bitmap;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "全屏截图失败");
                throw;
            }
        }

        /// <summary>
        /// 窗口截图
        /// </summary>
        public Bitmap? CaptureActiveWindow()
        {
            try
            {
                var activeWindow = NativeMethods.GetForegroundWindow();
                if (activeWindow == IntPtr.Zero)
                {
                    _logger.LogWarning("没有找到活动窗口");
                    return null;
                }

                if (!NativeMethods.GetWindowRect(activeWindow, out var rect))
                {
                    _logger.LogWarning("无法获取窗口矩形");
                    return null;
                }

                var width = rect.Right - rect.Left;
                var height = rect.Bottom - rect.Top;
                
                if (width <= 0 || height <= 0)
                {
                    _logger.LogWarning("窗口大小无效: {Width}x{Height}", width, height);
                    return null;
                }

                var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
                using var graphics = Graphics.FromImage(bitmap);
                graphics.CopyFromScreen(rect.Left, rect.Top, 0, 0, new System.Drawing.Size(width, height), CopyPixelOperation.SourceCopy);
                
                _logger.LogDebug("窗口截图完成: {Width}x{Height}", width, height);
                return bitmap;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "窗口截图失败");
                throw;
            }
        }

        /// <summary>
        /// 区域截图
        /// </summary>
        public void CaptureRegion()
        {
            try
            {
                // 创建截图选择窗口
                var selectionWindow = new ScreenCaptureWindow();
                selectionWindow.ScreenshotTaken += OnScreenshotTaken;
                selectionWindow.ShowDialog();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "区域截图失败");
            }
        }

        /// <summary>
        /// 指定区域截图
        /// </summary>
        public Bitmap CaptureRegion(Rectangle region)
        {
            try
            {
                var bitmap = new Bitmap(region.Width, region.Height, PixelFormat.Format32bppArgb);
                using var graphics = Graphics.FromImage(bitmap);
                graphics.CopyFromScreen(region.X, region.Y, 0, 0, region.Size, CopyPixelOperation.SourceCopy);
                
                _logger.LogDebug("区域截图完成: {X},{Y} {Width}x{Height}", region.X, region.Y, region.Width, region.Height);
                return bitmap;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "区域截图失败");
                throw;
            }
        }

        /// <summary>
        /// 保存截图到文件
        /// </summary>
        public string SaveScreenshot(Bitmap bitmap, string? fileName = null)
        {
            try
            {
                var screenshotsDir = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    "DesktopHelper", "Screenshots");
                
                Directory.CreateDirectory(screenshotsDir);
                
                fileName ??= $"Screenshot_{DateTime.Now:yyyyMMdd_HHmmss}.png";
                var filePath = Path.Combine(screenshotsDir, fileName);
                
                bitmap.Save(filePath, ImageFormat.Png);
                _logger.LogInformation("截图已保存: {FilePath}", filePath);
                
                return filePath;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存截图失败");
                throw;
            }
        }

        /// <summary>
        /// 截图并钉到桌面
        /// </summary>
        public void CaptureAndPin(Bitmap bitmap)
        {
            try
            {
                var filePath = SaveScreenshot(bitmap);
                _pinnedImageService.PinImageToDesktop(filePath);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "截图并钉图失败");
            }
        }

        private void OnScreenshotTaken(object? sender, ScreenshotTakenEventArgs e)
        {
            try
            {
                if (e.Screenshot != null)
                {
                    Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 截图完成，打开编辑窗口...");
                    
                    // 在UI线程上打开编辑窗口
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        var editWindow = new ScreenshotEditWindow(e.Screenshot);
                        editWindow.Show();
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理截图结果失败");
                Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 处理截图结果失败: {ex.Message}");
            }
        }

        private System.Windows.Media.Imaging.BitmapSource BitmapToImageSource(Bitmap bitmap)
        {
            using var memory = new MemoryStream();
            bitmap.Save(memory, ImageFormat.Bmp);
            memory.Position = 0;
            
            var bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
            bitmapImage.Freeze();
            
            return bitmapImage;
        }
    }

    // Windows API 声明
    internal static partial class NativeMethods
    {
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        internal static extern IntPtr GetForegroundWindow();

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
        internal struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
    }

    // 截图事件参数
    public class ScreenshotTakenEventArgs : EventArgs
    {
        public Bitmap? Screenshot { get; set; }
        public bool PinToDesktop { get; set; }
    }
}